import os
import shutil

#文件重命名，文件名中包含+符号url请求的时候会自动转换成%20，造成附件资源无法访问到
def get_all_files(directory):
    try:
        # 获取目录下的所有文件和文件夹
        all_files = os.listdir(directory)
        # 过滤出文件（排除文件夹）并且文件名包含 '+'
        files = [f for f in all_files if os.path.isfile(os.path.join(directory, f)) and '+' in f]
        return files
    except Exception as e:
        print(f"获取文件列表失败: {str(e)}")
        return []

def rename_and_copy_files(source_directory, target_directory):
    # 确保目标目录存在
    if not os.path.exists(target_directory):
        os.makedirs(target_directory)

    files = get_all_files(source_directory)
    for file_name in files:
        # 构建旧文件路径
        old_file_path = os.path.join(source_directory, file_name)
        # 构建新文件名（去掉 '+')
        new_file_name = file_name.replace('+', '')
        # 构建新文件路径
        new_file_path = os.path.join(target_directory, new_file_name)

        # 检查新文件名是否已经存在
        if os.path.exists(new_file_path):
            print(f"重命名失败: {old_file_path} -> {new_file_path}, 错误信息: 新文件名已存在")
            continue

        try:
            # 复制文件到目标目录并重命名
            shutil.copy(old_file_path, new_file_path)
            print(f"复制并重命名成功: {old_file_path} -> {new_file_path}")
        except Exception as e:
            print(f"复制并重命名失败: {old_file_path}, 错误信息: {str(e)}")

if __name__ == "__main__":
    input_directory = "F:\\knowledge3\\"  # 输入文件夹路径
    output_directory = "F:\\knowledge3\\word"  # 输出文件夹路径
    rename_and_copy_files(input_directory, output_directory)
